import {Component, OnInit} from '@angular/core';
import {Channel} from "../channel";
import {Router, ActivatedRoute} from "@angular/router";
import {MsgChannelService} from "../msgChannel.service";
import {ResponseUtil} from "../../../../../util/response-util";
import {MsgResult} from "../../../../../models/msg-result";
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../../util/page-subject";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {MsgConstants} from "../../../../../constants/constants";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {DataStorageUtil} from "../../../../../util/data-storage-util";

declare var $;
declare var moment;
declare var datepicker;

@Component({
  selector: 'app-channel-update',
  templateUrl: './channel-update.component.html',
  styleUrls: ['./channel-update.component.css']
})
export class ChannelUpdateComponent implements OnInit {

  //声明实例
  channels: Channel;

  config;

  receivers: Array<any> = [];

  channelsForm: FormGroup;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private channelService: MsgChannelService,
              private dialogService: OneDialogService,
              private responseUtil: ResponseUtil,
              private dataStorageUtil: DataStorageUtil,
              private fb: FormBuilder,) {
    this.initObject();
  }


  ngOnInit() {
    //初始化表单
    this.initTime();
    this.pushPage();
    if (!!this.route.snapshot.params['tag']) {
      this.initFormData();
    } else {
      this.initUpdateFrom();
    }
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("报警管理", "");
    this.pageSubject.pushPage("报警通道管理", "修改", path);

  }

  /**
   * 接收发送人数据后重新赋值
   */
  initFormData() {
    this.channels = this.channelsForm.value;
    this.channels.id = this.dataStorageUtil.get("alarmid");
    this.channels.alarmName = this.dataStorageUtil.get("alarmName");
    this.channels.type = this.dataStorageUtil.get("type");
    this.channels.sendMode = this.dataStorageUtil.get("sendMode");
    this.channels.level = this.dataStorageUtil.get("level");

    this.receivers = JSON.parse(this.dataStorageUtil.get("receiver"));
    let receiverName = "";
    let receiver = "";
    this.receivers.forEach(function (value) {
      receiverName += value.name + ",";
      receiver += value.id + "|" + value.type + ",";
    }, this);

    this.channels.receiver = receiver;
    this.channels.receiverName = receiverName;
    this.channels.isReal = this.dataStorageUtil.get("isReal");
    this.channels.startTime = this.dataStorageUtil.get("startTime");
    this.channels.endTime = this.dataStorageUtil.get("endTime");
    this.channels.isUse = this.dataStorageUtil.get("isUse");

    if (this.channels.isReal == "0") {
      $("#channel_update_startTime_div").show();
      $("#channel_update_endTime_div").show();
    }
    // console.log(this.channels);
    this.channelsForm.patchValue(this.channels);
  }

  //修改通道信息
  onSubmit() {
    this.channels = this.channelsForm.value;
    this.channels.startTime = $("#channel_update_startTime").val();
    this.channels.endTime = $("#channel_update_endTime").val();

    // console.log(JSON.stringify(this.channels));
    this.channelService.updateChannel(this.channels).subscribe(
      result => this.responseUtil.success(result, this.processUpdateResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelChannelUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //取消修改资源
  cancelChannelUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.channels = new Channel("", "", "1", "1", "1", "", "", "1", "", "", "0");
    this.buildForm();
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.channelsForm = this.fb.group({
      'id': [this.channels.id],
      'alarmName': [this.channels.alarmName, [
        Validators.required
      ]],
      'type': [this.channels.type],
      'sendMode': [this.channels.sendMode],
      'level': [this.channels.level],
      'receiver': [this.channels.receiver],
      'receiverName': [this.channels.receiverName],
      'isReal': [this.channels.isReal],
      'startTime': [this.channels.startTime],
      'endTime': [this.channels.endTime],
      'isUse': [this.channels.isUse],
    });

    this.channelsForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.channelsForm) {
      return;
    }
    const form = this.channelsForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'alarmName': ''
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'alarmName': {
      'required': '名称不能为空'
    }
  };

  /**
   * 通过id查询
   */
  initUpdateFrom() {
    //获取路由参数
    let id = this.route.snapshot.params["id"];
    this.channelService.getChannelById(id).subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.channels = result.data;
      this.channelsForm.patchValue(this.channels);
      if (this.channels.isReal == "0") {
        $("#channel_update_startTime_div").show();
        $("#channel_update_endTime_div").show();
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //初始化日期插件
  initTime() {
    let timeData = moment().format("YYYY-MM-DD HH:mm");
    this.config = {
      timePicker: true,
      timePickerIncrement: 1,
      singleDatePicker: true,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      locale: {
        format: "YYYY-MM-DD HH:mm",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      startDate: timeData,
      endDate: timeData
    };
    $("#channel_update_startTime").daterangepicker(this.config);
    $("#channel_update_endTime").daterangepicker(this.config);
  }

  noClickFun(e) {
    $("#channel_update_startTime_div").show();
    $("#channel_update_endTime_div").show();
  }

  yesClickFun(e) {
    $("#channel_update_startTime_div").hide();
    $("#channel_update_endTime_div").hide();
    $("#channel_update_startTime").val("");
    $("#channel_update_endTime").val("");
  }

  //跳转发送人页面
  getReceiver() {
    this.channels = this.channelsForm.value;
    this.dataStorageUtil.set("alarmid", this.channels.id);
    this.dataStorageUtil.set("alarmName", this.channels.alarmName);
    this.dataStorageUtil.set("type", this.channels.type);
    this.dataStorageUtil.set("sendMode", this.channels.sendMode);
    this.dataStorageUtil.set("level", this.channels.level);
    this.dataStorageUtil.set("isReal", this.channels.isReal);
    this.dataStorageUtil.set("startTime", $("#channel_update_startTime").val());
    this.dataStorageUtil.set("endTime", $("#channel_update_endTime").val());
    this.dataStorageUtil.set("isUse", this.channels.isUse);
    this.router.navigate(['../assign-receiver', {
      id: this.route.snapshot.params["id"],
      initReceiver: this.channels.receiver
    }], {relativeTo: this.route});
  }
}
